const express = require('express')
const fs = require('fs')
const multer = require('multer')
const config = require(process.cwd() + '/src/config/config')
const tiles = require(process.cwd() + '/src/utils/tiles')
const fileUtils = require(process.cwd() + '/src/utils/file')

let router = express.Router()

// 通过 filename 属性定制
var storage = multer.diskStorage({
  destination (req, file, callback) {
    // 大图保存的路径，暂存在images文件夹中
    callback(null, config.imagesPath)
  },
  filename (req, file, callback) {
    // 大图保存的名称
    callback(null, file.originalname)
  }
});

// 通过 storage 选项来对 上传行为 进行定制化
var upload = multer({ storage: storage })

// 执行操作
const doAction = async (req) => {
  const file = req.file
  // 先打开tileset文件，获取信息
  const tileset = req.body.tileset
  const settingPath = config.tilesetsPath + tileset + '.json'
  let setting = await fs.promises.readFile(settingPath)
  setting = JSON.parse(setting)
  
  // 获取大图源文件路径
  const imageOriginPath = config.imagesPath + file.originalname
  
  // 分割大图为图集单元并保存
  const addList = await tiles.addTilesetByImage(imageOriginPath, tileset, setting.itemWidth, setting.itemHeight, setting.colNum)
  // 删除原图片
  await fs.promises.unlink(imageOriginPath)
  
  // 将新加入的内容保存入setting
  setting.list = setting.list.concat(addList)
  const buffer = JSON.stringify(setting)
  await fs.promises.writeFile(settingPath, buffer)
  return setting
}

/* GET users listing. */
router.post('/', upload.single('image'), function(req, res) {
  const tileset = req.body.tileset
  
  doAction(req).then((setting) => {
    setting.list = tiles.tileImageSrc(setting.list, tileset)
    res.json(setting)
  })
  .catch((err) => {
    console.log(err)
    res.sendStatus(500)
  })
})

module.exports = router
